package org.bultreebank.extractor;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.bultreebank.document_repository.impl.IndexesDocumentsImpl;
import org.bultreebank.index.utils.Constants;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

import clark.dom.impl.DOMFactory;

public class CLaRKExtractor extends RelevantContentExrtactor implements Constants
{
	public CLaRKExtractor (IndexesDocumentsImpl documentsManager)
	{
		super(documentsManager);
	}
	
	
	@Override
	public Document getFormatedDocument(String[] matchingDocIDs)throws Exception
	{
		if (matchingDocIDs == null || matchingDocIDs.length == 0)
			return null;
		Map<String, Map<String, Set<String>>> result = super.getFormattedResultList(matchingDocIDs);
		Document resultDoc = DOMFactory.getEmptyDocument();
		Element root = resultDoc.createElement("result");
		resultDoc.appendChild(root);
		Set<String> contexts = result.keySet();
		Iterator<String> contextsIter = contexts.iterator();
		while (contextsIter.hasNext())
		{
			String contextID = contextsIter.next();
			Element contextElem = resultDoc.createElement(CONTEXT);
			contextElem.setAttribute(ID_ATTRIBUTE, contextID);
			root.appendChild(contextElem);
			Map<String, Set<String>> IDs = result.get(contextID);
			Iterator<String> docIDsIter = IDs.keySet().iterator();
			while (docIDsIter.hasNext())
			{
				try
				{
					String docID = docIDsIter.next();
					Element docElem = resultDoc.createElement(DOCUMENT);
					docElem.setAttribute(ID_ATTRIBUTE, docID);
					contextElem.appendChild(docElem);
					Set<String> parts = IDs.get(docID);
					Text t = resultDoc.createTextNode(parts.toString());
					docElem.appendChild(t);
				}
				catch (NullPointerException e)
				{
					e.printStackTrace();
					throw new Exception ("There is an error in the Search Engine Repository!\nDelete it and reindex the data!");
				}
			}
		}
		return resultDoc;
	}
}
